package com.sense.kukoo.common.media.playlist

import com.sense.kukoo.common.media.Kukoo
import com.sense.kukoo.common.media.bean.LocalMediaListItemBean
import com.sense.kukoo.common.repo.Repo
import com.sense.kukoo.lib_logger.LoggerManager

class MusicPlayListImpl {

    private val TAG: String = javaClass.simpleName

    fun play(bookItems: LocalMediaListItemBean) {
        val position:Int = Repo.playlist.add(bookItems)
        Repo.playlistPosition.set(position)
        Kukoo.play.play(bookItems)
        //刷新播放列表
        Kukoo.watcher.dispatchEvent {
            onPlayListChanged()
        }
    }

    fun play(index:Int){
        val next = Repo.playlist.get().get(index)
        Repo.playlistPosition.set(index)
        Kukoo.play.play(next)
        //刷新播放列表
        Kukoo.watcher.dispatchEvent {
            onPlayListChanged()
        }
    }

    fun delete(book :LocalMediaListItemBean){
        val deletePosition = Repo.playlist.delete(book)
        if(deletePosition == -1){
            //找不到要删除的
            LoggerManager.e(TAG, "找不到要删除的 -> ${book}")
            return
        }
        //设置播放状态，根据状态及currentPosition进行设置
        val currentPosition = Repo.playlistPosition.get()
        if(deletePosition == currentPosition){
            //当前播放
            Kukoo.play.stop()
            Repo.playlistPosition.set(-1)
        }
        //刷新播放列表
        Kukoo.watcher.dispatchEvent {
            onPlayListChanged()
        }
    }

    fun deleteAll(){
        Repo.playlist.deleteAll()
        Kukoo.play.stop()
        Repo.playlistPosition.set(-1)
        //刷新播放列表
        Kukoo.watcher.dispatchEvent {
            onPlayListChanged()
        }
    }

    fun getList():ArrayList<LocalMediaListItemBean> = Repo.playlist.get()

    //播放完毕
    fun onMusicCompletion(bookItems: LocalMediaListItemBean){
        //
        fun playMusic(next:LocalMediaListItemBean?){
            if (next == null){
                Repo.playlistPosition.set(-1)
                Kukoo.play.stop()
            }else{
                Repo.playlistPosition.set(0)
                Kukoo.play.play(next)
            }
            //刷新播放列表
            Kukoo.watcher.dispatchEvent {
                onPlayListChanged()
            }
        }

        val next = Repo.playlist.deleteFirstAndGetNext(bookItems)
        playMusic(next)
    }

}